package org.wisdom.sso.boe.controller;

import cn.hutool.core.net.URLEncoder;
import com.jingantech.ngiam.Format;
import com.jingantech.ngiam.ResponseBody;
import com.jingantech.ngiam.cas.CasService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 用户登陆接口
 *
 * @author zhangzhiyan
 * @date 2021/11/10 14:56
 **/
//@Controller
@Slf4j
public class SsoLoginController1 {

    @Value("${sso.uri}")
    private String ssoUri;

    @Value("${sso.loginUri}")
    private String loginUri;

    @Value("${sso.validateUri}")
    private String validateUri;

    @Value("${service.uri}")
    private String serviceUri;

    @Value("${boe.uri}")
    private String boeUri;

    @GetMapping("/")
    public String index(@RequestParam(value = "ticket", required = false) String ticket, Model model) {

        URLEncoder urlEncoder = new URLEncoder();
        String url = this.ssoUri + this.loginUri;
        model.addAttribute("ssoLoginUrl", url);
        model.addAttribute("boeUrl", this.boeUri);
        model.addAttribute("service", urlEncoder.encode(this.serviceUri, StandardCharsets.UTF_8));
        model.addAttribute("isLogin", false);
        try {
            ResponseBody responseBody = CasService.casValidate(url,ticket,urlEncoder.encode(this.serviceUri, StandardCharsets.UTF_8), Format.json);
            model.addAttribute("isLogin", true);
            model.addAttribute("userName", responseBody.getUser());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "user";
    }

    @GetMapping("/user")
    public String user(ModelMap modelMap) {
        modelMap.addAttribute("user", "authentication");
        return "user";
    }
}
